/***
 * Excerpted from "Stripes: and Java Web Development is Fun Again",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/fdstr for more book information.
***/
package stripesbook.action.user.folders;

import java.util.List;
import javax.annotation.security.PermitAll;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.HttpCache;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.stripesbook.rayures.view.ViewObject;
import stripesbook.model.Attachment;
import stripesbook.model.Folder;
import stripesbook.model.Message;
import stripesbook.view.MessageAction;
import stripesbook.view.MessageListView;

@HttpCache(allow=false)
@PermitAll
public class MessageListActionBean extends FoldersActionBean {
  @DefaultHandler
  public void list() {
  }
  public Resolution delete() {
    Folder folder = getContext().getCurrentFolder();

    if (Folder.TRASH.equals(folder.getName())) {
      for (Message message : selectedMessages) {
        for (Attachment attachment : message.getAttachments()) {
          attachmentDao.deleteFile(attachment);
        }
        messageDao.delete(message);
      }
    }
    else {
      Folder trash =
        folderDao.findByName(Folder.TRASH, getUser());
      for (Message message : selectedMessages) {
        messageDao.addMessageToFolder(message, trash);
      }
    }
    messageDao.commit();
    return new RedirectResolution(getClass());
  }
  public Resolution moveToFolder() {
    for (Message message : selectedMessages) {
      messageDao.addMessageToFolder(message, selectedFolder);
    }
    messageDao.commit();
    return new RedirectResolution(getClass());
  }
  @Validate(encrypted=true,
    required=true, on={"delete", "moveToFolder"})
  private List<Message> selectedMessages;
  public List<Message> getSelectedMessages() {
    return selectedMessages;
  }
  public void setSelectedMessages(List<Message> selectedMessages) {
    this.selectedMessages = selectedMessages;
  }
  @Validate(encrypted=true,
    required=true, on="moveToFolder")
  private Folder selectedFolder;
  public Folder getSelectedFolder() {
    return selectedFolder;
  }
  public void setSelectedFolder(Folder selectedFolder) {
    this.selectedFolder = selectedFolder;
  }

  public ViewObject<?> getMessageAction() {
    return tag(MessageAction.class).folders(getUser().getFolders());
  }

  @Override
  public Object getView() {
    return tag(MessageListView.class);
  }
}
